package ruifeng.zcj.dig.ui.base;

import android.content.Context;
import android.os.AsyncTask;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.View;

import com.bzh.recycler.ExRecyclerView;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;

import java.io.Serializable;
import java.lang.ref.WeakReference;

import butterknife.Bind;
import cn.bingoogolapple.androidcommon.adapter.BGAOnRVItemClickListener;
import cn.bingoogolapple.androidcommon.adapter.BGAOnRVItemLongClickListener;
import cn.bingoogolapple.androidcommon.adapter.BGARecyclerViewAdapter;
import ruifeng.zcj.dig.R;
import ruifeng.zcj.dig.base.MyApp;
import ruifeng.zcj.dig.base.bean.Base;
import ruifeng.zcj.dig.base.cache.CacheApi;
import ruifeng.zcj.mybase.base.App;
import ruifeng.zcj.mybase.base.BaseFragment;
import ruifeng.zcj.mybase.base.RxManager;
import ruifeng.zcj.mybase.base.utils2.CacheManager;
import ruifeng.zcj.mybase.base.utils2.StringUtils;
import ruifeng.zcj.mybase.base.utils2.TDevice;

/**
 * Created by Administrator on 2016/9/22 0022.
 */
public abstract class RefreshRecyclerFragment extends BaseFragment<RefreshRecyclePresenter, RefreshRecycleModel> implements BGAOnRVItemClickListener, BGAOnRVItemLongClickListener, SwipeRefreshLayout.OnRefreshListener
        , ExRecyclerView.OnLoadMoreListener {

    @Bind(R.id.refreshLayout)
    protected SwipeRefreshLayout swipeRefreshLayout;

    @Bind(R.id.recyclerView)
    protected ExRecyclerView recyclerView;

    protected BGARecyclerViewAdapter mMomentAdapter;
    protected RxManager mRxManager = null;
    protected int mCurrentPage = 0;

    public static final int STATE_NONE = 0;// 不在刷新
    public static final int STATE_REFRESHING = 1;// 正在刷新
    public static final int STATE_PRESSING = 2;// 正在下拉但还没有到刷新的状态
    public static final int STATE_CACHE_LOADING = 3;

    public static final int LOAD_MODE_DEFAULT = 1; // 默认的下拉刷新,小圆圈
    public static final int LOAD_MODE_UP_DRAG = 2; // 上拉到底部时刷新
    public static final int LOAD_MODE_CACHE = 3; // 缓存,ErrorLayout显示情况
    public static final int STATE_LOADMORE = 2;
    public static final int STATE_NOMORE = 3;
    public static final int STATE_REFRESH = 1;
    public static final int STATE_PRESSNONE = 4;// 正在下拉但还没有到刷新的状态

    public int mState = STATE_NONE;
    private AsyncTask<String, Void, Base> mCacheTask;
    private AsyncTask<Void, Void, Void> mSaveCacheTask;


    @Override
    protected void initFragmentConfig(View view) {
        if (recyclerView == null) {
           // recyclerView = (ExRecyclerView) view.findViewById(R.id.recyclerView);
            recyclerView = (ExRecyclerView) getViewById(R.id.recyclerView);
        }
        if (OnLoadingMore()) {
            recyclerView.setOnLoadingMoreListener(this);
        }

        if (getRefreshable()) {
            swipeRefreshLayout.setOnRefreshListener(this);
            swipeRefreshLayout.setColorSchemeResources(android.R.color.holo_blue_bright,
                    android.R.color.holo_green_light,
                    android.R.color.holo_orange_light,
                    android.R.color.holo_red_light);
        }

        mMomentAdapter = getAdapter();

        mMomentAdapter.setOnRVItemClickListener(this);
        mMomentAdapter.setOnRVItemLongClickListener(this);
        recyclerView.setAdapter(mMomentAdapter);
    }

    /****
     * 判断是否需要加载更多
     ***/
    protected boolean OnLoadingMore() {
        return true;
    }

    /***
     * 加载更多
     **/
    @Override
    public void onLoadingMore() {
        mCurrentPage++;
        mState = STATE_LOADMORE;
        showLoadingDialog("加载更多");// 记得要关闭这个Dialog
        requestData(false);
    }

    protected abstract BGARecyclerViewAdapter getAdapter();

    @Override
    protected int getContentView() {
        return R.layout.refresh_recy;
    }


    @Override
    protected void onFirstUserVisible() {
        if (requestDataIfViewCreated()) {
            mState = STATE_NONE;
            requestData(false);
        }

    }

    protected void requestData(boolean refresh) {
        if (mRxManager == null) {
            mRxManager = RxManager.getInstance();
        }
        String key = getCacheKey();
        if (isReadCacheData(refresh)) {
            readCacheData(key);
        } else {
            // 取新的数据
            sendRequestData();
        }
        hideSwipeRefreshing();
    }

    /****
     * 读取缓存
     **/
    protected void readCacheData(String key) {
        cancelReadCacheTask();
        mCacheTask = new CacheTask(getActivity());
        mCacheTask.execute(key);
    }

    /****
     * 保存数据
     **/
    protected void saveObject(String key,Base base) {
        cancelSaveCacheTask();
        mSaveCacheTask = new SaveCacheTask(getActivity(), base, key).execute();
    }

    /****
     * 网络请求数据
     **/
    protected void httpRequest(String key,Base base) {
        cancelSaveCacheTask();
        mSaveCacheTask = new HttpTask(getActivity(), base, key).execute();
    }

    protected class HttpTask extends AsyncTask<Void, Void, Void> {
        private final WeakReference<Context> mContext;
        private final Serializable seri;
        private final String key;

        private HttpTask(Context context, Base seri, String key) {
            mContext = new WeakReference<Context>(context);
            this.seri = seri;
            this.key = key;
        }
        @Override
        protected Void doInBackground(Void... params) {
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);
        }
    }

    protected class SaveCacheTask extends AsyncTask<Void, Void, Void> {
        private final WeakReference<Context> mContext;
        private final Serializable seri;
        private final String key;

        private SaveCacheTask(Context context, Base seri, String key) {
            mContext = new WeakReference<Context>(context);
            this.seri = seri;
            this.key = key;
        }

        @Override
        protected Void doInBackground(Void... params) {
        //    CacheManager.saveObject(App.getAppContext(), base, getCacheKey());

            CacheManager.saveObject(mContext.get(), seri, key);
            return null;
        }
    }

    protected void cancelReadCacheTask() {
        if (mCacheTask != null) {
            mCacheTask.cancel(true);
            mCacheTask = null;
        }
    }
    protected void cancelSaveCacheTask() {
        if (mSaveCacheTask != null) {
            mSaveCacheTask.cancel(true);
            mSaveCacheTask = null;
        }
    }

    private class CacheTask extends AsyncTask<String, Void, Base> {
        private final WeakReference<Context> mContext;

        private CacheTask(Context context) {
            mContext = new WeakReference<Context>(context);
        }

        @Override
        protected Base doInBackground(String... params) {
            Base seri = (Base) CacheManager.readObject(App.getAppContext(),
                    params[0]);
            if (seri == null) {
                return null;
            }
            return seri;
        }

        @Override
        protected void onPostExecute(Base base) {
            super.onPostExecute(base);
            if (base != null) {
                executeOnLoadDataSuccess(base);
            } else {
                sendRequestData();
                showSnackBar("没有缓存");
            }
            showSnackBar("读取缓存完成");
        }
    }

    // 请求数据成功之后该做的事情
    protected void executeOnLoadDataSuccess(Serializable seri) {
        hideSwipeRefreshing();
        // 判断是否登录失效
        Base mbase = CacheApi.readUserMessage("login");
        if (mbase == null) {// 退出登录
            MyApp myApp = (MyApp) MyApp.getInstance();
            myApp.Logout();
            showSnackBar("跳转到登录界面去");
        }
        if (seri == null) {
            return;
        }
        if (mCurrentPage == 0) {
            if (mMomentAdapter != null) {
                mMomentAdapter.clear();
            }
        }
        mState = STATE_NOMORE;
    }

    /***
     * 判断是否需要读取缓存的数据
     *
     * @param refresh
     * @return
     * @author
     */
    protected boolean isReadCacheData(boolean refresh) {
        String key = getCacheKey();
        if (!TDevice.hasInternet()) {
            return true;
        }
        // 第一页若不是主动刷新，缓存存在，优先取缓存的
        if (CacheManager.isExistDataCache(App.getAppContext(), key) && !refresh
                && mCurrentPage == 0) {
            return true;
        }
        // 其他页数的，缓存存在以及还没有失效，优先取缓存的
        if (CacheManager.isExistDataCache(getActivity(), key)
                && !CacheManager.isCacheDataFailure(getActivity(), key)
                && mCurrentPage != 0) {
            return true;
        }
        return false;
    }

    /****
     * 网络请求数据具体的子类实现
     **/
    protected void sendRequestData() {
        showLoadingDialog("加载数据");
    }

    /****
     * 记录最后一次下拉刷新时间
     **/
    protected void sendRequestDataSucess(String result) {
        dismissLoadingDialog();
       if (result.contains("err")){
           return;
       }
        if (mCurrentPage == 0 && needAutoRefresh()) {
            CacheApi.putToLastRefreshTime(getCacheKey(),
                    StringUtils.getCurTimeStr());
        }
        hideSwipeRefreshing();
    }


    /***
     * 获取缓存的key
     **/
    protected String getCacheKey() {
        return new StringBuilder(getCacheKeyPrefix()).append("_")
                .append(mCurrentPage).toString();
    }

    protected String getCacheKeyPrefix() {
        return "one";
    }

    /***
     * 允许下拉刷新
     */
    public boolean getRefreshable() {
        return true;
    }

    /**
     * 是否需要请求数据
     **/
    protected boolean requestDataIfViewCreated() {
        return true;
    }

    /****
     * 下拉刷新效果
     **/
    @Override
    public void onRefresh() {
        if (mState == STATE_REFRESHING && getRefreshable())
            return;
        mCurrentPage = 0;
        mState = STATE_REFRESHING;
        requestData(true);

    }

    // 是否需要自动刷新
    protected boolean needAutoRefresh() {
        return true;
    }

    /***
     * 自动刷新的时间
     * <p/>
     * 默认：自动刷新的时间为半天时间
     *
     * @return
     * @author
     */
    protected long getAutoRefreshTime() {
        return 12 * 60 * 60;
    }

    // 是否到时间去刷新数据了
    protected boolean onTimeRefresh() {
        String lastRefreshTime = CacheApi.getLastRefreshTime(getCacheKey());
        String currTime = StringUtils.getCurTimeStr();
        long diff = StringUtils.calDateDifferent(lastRefreshTime, currTime);
        return needAutoRefresh() && diff > getAutoRefreshTime();
    }

    /***
     * 自动刷新
     **/
    @Override
    protected void onUserInvisible() {
        // 判断下是否要重新请求数据
        if (getRefreshable() && onTimeRefresh()) {
            onRefresh();
        }
    }

    @Override
    protected void cleanMemory() {

    }

    /****
     * 把所有的异步请求都关闭
     **/
    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mRxManager != null) {
            mRxManager.clear();
        }
        cancelReadCacheTask();// 关闭读取数据
        cancelSaveCacheTask();// 关闭缓存数据
    }


    public void showSwipeRefreshing() {
        if (swipeRefreshLayout != null) {
            swipeRefreshLayout.setRefreshing(true);
        }
    }


    public void hideSwipeRefreshing() {
        if (swipeRefreshLayout != null) {
            swipeRefreshLayout.setRefreshing(false);
        }
    }


    public boolean isRefreshing() {
        if (swipeRefreshLayout != null) {
            return swipeRefreshLayout.isRefreshing();
        }
        return false;
    }


    public boolean isLoadingMore() {
        return recyclerView != null && recyclerView.isLoadingMore();
    }

    public ExRecyclerView getRecyclerView() {
        if (recyclerView != null)
            return recyclerView;
        else return null;
    }

    public SwipeRefreshLayout getSwipeRefreshLayout() {
        if (swipeRefreshLayout != null)
            return swipeRefreshLayout;
        else return null;
    }

    public void finishLoadMore() {
        if (recyclerView != null)
            recyclerView.finishLoadingMore();
    }

    protected void onRefreshNetworkSuccess(){}



}
